package com.example.hosptial.newController;

import com.example.hosptial.model.view.DoctorView;
import com.example.hosptial.service.AdmissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import jakarta.servlet.http.HttpSession;
import java.util.Map;
import java.util.HashMap;

/**
 * 病人出院管理Controller
 */
@Controller
@RequestMapping("/doctor/discharge")
public class DischargeController {

    private static final Logger logger = LoggerFactory.getLogger(DischargeController.class);

    @Autowired
    private AdmissionService admissionService;

    /**
     * 显示出院管理页面
     */
    @GetMapping
    public String showDischargePage(HttpSession session, Model model) {
        DoctorView doctor = (DoctorView) session.getAttribute("doctor");
        if (doctor == null) {
            return "redirect:/doctor/auth/login";
        }
        return "doctor/discharge";
    }

    /**
     * 办理病人出院
     * @param patientId 病人ID
     * @param session HTTP会话
     * @return 处理结果
     */
    @PostMapping
    @ResponseBody
    public ResponseEntity<?> dischargePatient(
            @RequestParam Integer patientId,
            HttpSession session) {

        // 获取当前登录的医生信息
        DoctorView doctor = (DoctorView) session.getAttribute("doctor");

        if (doctor == null) {
            return ResponseEntity.status(401).body(Map.of(
                "code", 401,
                "message", "未登录或会话已过期"
            ));
        }

        try {
            // 调用服务层办理出院
            admissionService.dischargePatient(patientId, doctor.getDoctorId());
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "出院办理成功");
            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException e) {
            logger.warn("出院参数错误: {}", e.getMessage());
            return ResponseEntity.badRequest().body(Map.of(
                "code", 400,
                "message", e.getMessage()
            ));

        } catch (SecurityException e) {
            logger.warn("出院权限错误: {}", e.getMessage());
            return ResponseEntity.status(403).body(Map.of(
                "code", 403,
                "message", e.getMessage()
            ));

        } catch (Exception e) {
            logger.error("出院处理失败: {}", e.getMessage());
            return ResponseEntity.status(500).body(Map.of(
                "code", 500,
                "message", "出院办理失败: " + e.getMessage()
            ));
        }
    }
}